<template>
  <div class="markdown-renderer" ref="container" v-html="processedMarkdown" @click="handleClick"></div>
</template>

<script lang="ts" setup>
import { computed } from 'vue';
import { marked } from 'marked';
import DOMPurify from 'dompurify';
import hljs from 'highlight.js';
import 'highlight.js/styles/github.css';
import type { MarkedExtension } from 'marked';
import he from 'he';

// 新增：让单回车也换行，并支持代码高亮
marked.setOptions({ breaks: true });
marked.use({
  hooks: {
    postprocess(html: string): string {
      // 用正则查找所有<pre><code class="language-xxx">...</code></pre>
      return html.replace(/<pre><code class="language-(\w+)">([\s\S]*?)<\/code><\/pre>/g, (match: string, lang: string, code: string) => {
        let highlighted = '';
        try {
          if (lang && hljs.getLanguage(lang)) {
            highlighted = hljs.highlight(code, { language: lang }).value;
          } else {
            highlighted = hljs.highlightAuto(code).value;
          }
        } catch (e) {
          highlighted = code;
        }
        return `<pre><code class="hljs ${lang}">${highlighted}</code></pre>`;
      });
    }
  }
});

const props = defineProps({
  markdown: {
    type: String,
    required: true
  },
  jumpToTime: {
    type: Function,
    required: true
  }
});

// 替换 @00:00:00 为可点击链接
const processMarkdown = (content: string) => {
  const withLinks = content.replace(/@(\d{2}:\d{2}:\d{2})/g, (match: string, time: string) => {
    return `<a href="javascript:void(0)" class="timestamp" data-time="${time}">${time}</a>`;
  });
  return withLinks;
};

// 整体渲染Markdown
const processedMarkdown = computed(() => {
  const html = marked.parse(props.markdown, { async: false }) as string;
  const withTimestampLinks = processMarkdown(html);
  // 先sanitize再解码实体
  return he.decode(DOMPurify.sanitize(withTimestampLinks));
});

// 处理点击事件
const handleClick = (event: MouseEvent) => {
  const target = event.target as HTMLElement;
  if (target.classList.contains('timestamp')) {
    const timeStr = target.getAttribute('data-time');
    if (timeStr && props.jumpToTime) {
      props.jumpToTime(timeStr)
    }
  }
};
</script>

<style scoped>
.timestamp {
  color: #1e90ff;
  text-decoration: underline;
  cursor: pointer;
  margin-left: 4px;
}
</style>
